/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ControllerAjax;

import GestionBDD.ControllerBDD;
import Main.StaticParams;
import Main.Toolbox;
import Model.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sik
 */
@WebServlet(name = "Zone", urlPatterns =
{
    "/Zone/*"
})
public class ControllerZone extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String pathInfo =  request.getPathInfo();
        int idCarte = Integer.parseInt(request.getParameter("idCarte"));
        Carte carte = getMapFromId(idCarte);
        
        if(pathInfo.equals("/add"))
        {
            String designation = request.getParameter("designation");
            String details = request.getParameter("details");
            String comm = request.getParameter("commentaires");
            String path = request.getParameter("path");

            if(designation != null)
            {
                Zone z = new Zone();
                z.setDesignation(designation);
                z.setDetails(details);
                z.setCommentaires(comm);
                z.setCarteidCarte(carte);
                carte.getZoneList().add(z);
                ControllerBDD.getINSTANCE().add(z);
                
                // Ajout des épingles
                List<Epingle> le = extractPinsFromPath(path, z);
                for(Epingle e : le)
                {
                    ControllerBDD.getINSTANCE().add(e);
                }
                z.setEpingleList(le);
                
                // Renvoi de l'ID de la zone
                setUpResponse(response, z);
            }
        }
        else if(pathInfo.equals("/list"))
        {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/listZones.jsp");
            rd.forward(request, response);
        }
        else if(pathInfo.equals("/delete"))
        {
            int idZone = Integer.parseInt(request.getParameter("idZone"));
            List<Zone> lz = (List<Zone>)carte.getZoneList();
            Zone z = getZoneFromId(idZone);
            lz.remove(z);
            ControllerBDD.getINSTANCE().remove(z);
        }
        else if(pathInfo.equals("/update"))
        {
            System.out.println(request.getParameterMap());
            String designation = request.getParameter("designation");
            String details = request.getParameter("details");
            String comm = request.getParameter("commentaires");
            int idZone = Integer.parseInt(request.getParameter("idZone"));
            Zone z = getZoneFromId(idZone);
            if(!designation.equals(z.getDesignation()))
            {
                z.setDesignation(designation);
            }
            if(!details.equals(z.getDetails()))
            { 
                System.out.println(details);
                z.setDetails(details);
            }
            if(!comm.equals(z.getCommentaires()))
            {
                System.out.println(comm);
                z.setCommentaires(comm);
            }
            
            ControllerBDD.getINSTANCE().update(z);
        }
        else if(pathInfo.equals("/updatePosition"))
        {
            String path = request.getParameter("path");
            int idZone = Integer.parseInt(request.getParameter("idZone"));
            Zone z = getZoneFromId(idZone);
            List<Epingle> le = extractPinsFromPath(path, z);
            List<Epingle> ze = z.getEpingleList();
            List<Epingle> removeList = new ArrayList<Epingle>();
            
            for(int i = 0; i < ze.size(); i++)
            {
                if(le.size() > i)
                {
                    if(ze.get(i).getX() != le.get(i).getX() || ze.get(i).getY() != le.get(i).getY())
                    {
                        ze.get(i).setX(le.get(i).getX());
                        ze.get(i).setY(le.get(i).getY());
                        ControllerBDD.getINSTANCE().update(ze.get(i));
                    }
                }
                else
                {
                    removeList.add(ze.get(i));
                }
            }
            ze.removeAll(removeList);
            ControllerBDD.getINSTANCE().update(z);
            for(Epingle e : removeList)
            {
                ControllerBDD.getINSTANCE().remove(e);
            }
            
            for(int j = ze.size(); j<le.size(); j++)
            {
                ControllerBDD.getINSTANCE().add(le.get(j));
                ze.add(le.get(j));
            }
        }
        else if(pathInfo.equals("/pick"))
        {
            String idZone = request.getParameter("idZone");
            Utilisateur u = this.getUserFromName(request.getUserPrincipal().getName());
            
            if(idZone != null && u != null)
            {
                Zone z = this.getZoneFromId(Integer.parseInt(idZone));
                AttributionPK apk = new AttributionPK(z.getIdZone(), u.getIdUtilisateur());
                Attribution a = new Attribution(apk);
                a.setDate(new GregorianCalendar().getTime());
                a.setStatut(StaticParams.DEFAULT_ATTRIBUTION_STATUS);
                a.setUtilisateur(u);
                a.setZone(z);
                z.getAttributionList().add(a);
                u.getAttributionList().add(a);
                ControllerBDD.getINSTANCE().add(a);
                ControllerBDD.getINSTANCE().update(z);
            }
        }
    }
    
    private void setUpResponse(HttpServletResponse response, Zone z) throws IOException
    {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(z.xmlParse(false));
        response.getWriter().close();
    }
    
    public Utilisateur getUserFromName(String name)
    {
        List<Utilisateur> lu = (List<Utilisateur>)getServletContext().getAttribute("users");
        
        for(Utilisateur u : lu)
        {
            if(u.getLogin().equals(name))
            {
                return u;
            }
        }
        return null;
    }
    
    public Carte getMapFromId(int id)
    {
        List<Carte> lc = (List<Carte>)getServletContext().getAttribute("maps");
        
        for(Carte c : lc)
        {
            if(c.getIdCarte() == id)
            {
                return c;
            }
        }
        return null;
    }
    
    public Zone getZoneFromId(int id)
    {
        List<Carte> lc = (List<Carte>)getServletContext().getAttribute("maps");
        for(Carte c : lc)
        {
            for(Zone z : c.getZoneList())
            {
                if(z.getIdZone() == id)
                {
                    return z;
                }
            }
        }
        return null;
    }
    
    public List<Epingle> extractPinsFromPath(String path, Zone zone)
    {
        List<Epingle> le = new ArrayList<Epingle>();
        
        String[] pathArray = path.split(" ");
        int cursor = 0;
        int order = 1;
        int x = 0;
        int y = 0;
        
        for(String s : pathArray)
        {
            if(cursor == 1)
            {
                x = Integer.parseInt(s);
            }
            else if(cursor == 2)
            {
                y = Integer.parseInt(s);
                Epingle e = new Epingle();
                e.setX(x);
                e.setY(y);
                e.setOrdre(order);
                e.setZoneidZone(zone);
                le.add(e);
                order++;
                cursor = -1;
            }
            cursor++;
        }
        return le;
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
